﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Web.UI;
using BlogEngine.Core;
using System.Globalization;
using System.Text;
using System.Threading;

namespace _4mvcBlog.Core
{
    public class BaseController : Controller
    {

        #region 属性

        /// <summary>
        /// 获取或设置页面的标题
        /// </summary>
        protected string PageTitle
        {
            get
            {
                return ViewData["PageTitle"] as string ?? "";
            }
            set
            {
                if (BlogSettings.Instance.UseBlogNameInPageTitles)
                {
                    ViewData["PageTitle"] = (BlogSettings.Instance.Name + " | " + value);
                }
                else
                {
                    ViewData["PageTitle"] = value;
                }
            }
        }

        #endregion

        #region 添加分类列表到ViewData["Categories"]中

        /// <summary>
        /// 添加分类列表到ViewData["Categories"]中
        /// </summary>
        public void AddCategoriesViewData()
        {
            List<Category> categories = Category.Categories;
            ViewData["Categories"] = categories;
        }

        #endregion        

        #region 显示提示信息

        /// <summary>
        /// 显示提示信息
        /// </summary>
        /// <param name="msg">要显示的提示信息</param>
        /// <returns></returns>
        protected ActionResult ShowMsg(string msg)
        {
            return ShowMsg(new List<string>() { msg });
        }

        /// <summary>
        /// 显示提示信息
        /// </summary>
        /// <param name="msgs">要显示的提示信息列表</param>
        /// <returns></returns>
        protected ActionResult ShowMsg(List<string> msgs)
        {
            TempData["Messages"] = msgs;
            return RedirectToAction("Message");
        }

        [OutputCache(Location = OutputCacheLocation.None)]
        public virtual ActionResult Message()
        {
            return View(TempData["Messages"] as List<string>);
        }

        #endregion

        #region 使用Json.Net返回Json结果
        /// <summary>
        /// 使用Json.Net返回Json结果
        /// </summary>
        /// <param name="values">要序列化为Json格式的实体</param>
        /// <returns></returns>
        public ContentResult Json_Net(object values)
        {
            return Content(Newtonsoft.Json.JavaScriptConvert.SerializeObject(values), "application/json");
        }

        #endregion

        protected override void OnException(ExceptionContext filterContext)
        {
            ViewData["PageTitle"] = "出错了";
            base.OnException(filterContext);
        }
    }
}
